package com.pagepub.core.tag.validator;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

public class ValidateIp extends FormValidateBasic {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2072841505316685011L;

	private String rightimage;

	private String rightwordcolor;

	private String submitvalidate;

	public int doStartTag() throws JspException {
		JspWriter out = this.pageContext.getOut();

		try {
			out.print(validateip());
		} catch (IOException e) {
			// TODO 自动生成 catch 块

			e.printStackTrace();
		}
		// TODO 自动生成方法存根
		return super.doStartTag();
	}

	public String getRightimage() {
		return rightimage;
	}

	public void setRightimage(String rightimage) {
		this.rightimage = rightimage;
	}

	public String getRightwordcolor() {
		return rightwordcolor;
	}

	public void setRightwordcolor(String rightwordcolor) {
		this.rightwordcolor = rightwordcolor;
	}

	public String getSubmitvalidate() {
		return submitvalidate;
	}

	public void setSubmitvalidate(String submitvalidate) {
		this.submitvalidate = submitvalidate;
	}

	public StringBuffer validateip() {
		StringBuffer str = new StringBuffer();
		String emptyelement = "";
		String pluselement = "";
		if (this.submitvalidate.equalsIgnoreCase("true")) {
			emptyelement = "emptyelement(realname);";
			pluselement = " pluselement(realname);";
		}
		str.append("<script language=\"javascript\">");
		str.append("function  validateip(realvalue,spanname,realname){");
		str.append("var reg =/^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/g;");
		str.append(" realvalue =trim(realvalue);");
		str
				.append("if(realvalue!=\"\"){if(!reg.test(realvalue)||!(RegExp.$1 <256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256))");
		str.append("{ ");
		str.append("	message=\"对不起,您输入ip地址不正确!\";");
		str.append(" imgurl=\"<img src=\\\"" + this.getWrongimage()
				+ "\\\"/>\";");
		str.append(this.display());
		str.append(pluselement);
		str.append("}");
		str.append("else {");
		str.append("	message=\"恭喜！,您输入ip地址可以使用!\";");
		str.append(" imgurl=\"<img src=\\\"" + this.getRightimage()
				+ "\\\"/>\";");
		str
				.append("document.getElementById(spanname).innerHTML=imgurl+\"<font color=\\\""
						+ this.rightwordcolor + "\\\">\"+message+\"</font>\";");
		str.append(emptyelement);
		str.append("}");
		str.append("} } ");
		str.append("function  trim(str)");
		str.append("{");
		str
				.append(" for(var  i  =  0  ;  i<str.length  &&  str.charAt(i)==\" \" ;i++  )  ;");
		str
				.append("for(var  j  =str.length;  j>0  &&  str.charAt(j-1)==\" \"  ;  j--)  ;");
		str.append("if(i>j)  return  \"\"; ");
		str.append(" return  str.substring(i,j);");
		str.append("} ");
		str.append("</script>");
		return str;
	}
}
